<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/9 0009
 * Time: 15:24
 */

namespace app\index\controller;

use think\facade\Session;
use think\Controller;

class Login extends Controller
{
    const APPID  = 'wxf1061ff8bec446a0';
    const SECRET  = '32ea97f68e64ff5fc5a1598312f7d37e';
    const ADDR  = 'http://www.hlrork.com/';
    public function index(){
        return view("index");
    }

    public function login(){
        if(request()->post()){
            $data = request()->param();
            $member = db("member")->where("mobile",$data['val1'])->find();
            if(empty($member)){
               return ['state' => -1,'msg' => '账号或者密码错误'];
            }
            if($member['password'] != md5($data['val2'])){
                return ['state' => -1,'msg' => '账号或者密码错误'];
            }
            session('member_id',$member['id']);
            return ['state' => 200,'msg' => 'SUCCESS'];
        }
    }
    public function logout(){
        Session::delete('member_id');
//        $this->error('退出成功','/');
        $this->redirect('/');
    }

    //微信登录
    public function wxlogin(){
        //获取code
        $code = $_GET['code'] ?? 'false';
        //根据code获取access_token
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".self::APPID."&secret=".self::SECRET."&code=".$code."&grant_type=authorization_code";
        $obj_data = __curl($url);
        $arr_data = json_decode($obj_data,true);
//        根据access_token获取用户信息
        $user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$arr_data['access_token']."&openid=".$arr_data['openid'];
        $user_info_data = __curl($user_info_url);
        $user_arr_data = json_decode($user_info_data,true);
//        dump($user_arr_data);
        //判断用户是否是第一次登录
        $member = db("member")->where('openid',$user_arr_data['openid'])->find();
        if(empty($member)){
            $data = [
                'nickname' => $user_arr_data['nickname'],
                'head_img' => $user_arr_data['headimgurl'],
                'openid' => $user_arr_data['openid'],
                'type' => 1
            ];
            $member_id = db('member')->insertGetId($data);
            if($member_id > 0){
                session('member_id',$member_id);
            }
        }else{
            session('member_id',$member['id']);
        }
        $this->redirect('/');
    }

}